package com.qiantu.phone.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;

import com.qiantu.phone.R;
import com.qiantu.phone.app.AppApplication;

/**
 * @ClassName KHCurtainSeek
 * @Description TODO
 * @Author ShiJunqiang
 * @Date 2021/6/11 21:38
 * @Version 1.0
 */
public class RollerShutterSeek extends View {
    private boolean isReadyDrag;
    public int mTrackLength;//轨道长度
    public Rect mRootRect;
    public int mMax = 100;
    public int mProgress = 0;
    protected OnChangeListener mOnChangeListener;
    public int clickThreshold;
    public final int CAN_DRAG_TIME = 0;
    private int topLineHeight;
    private int bottomHeight;
    private int curtainMarginLeftRight;
    private float progressTextSize;
    private int progressTextColor;
    private Paint mPaint;
    private Paint mTextPaint;
    private Path topLinePath;
    private RectF bgRectF;
    private int curtainFillHeight;
    private int curtainGapHeight;
    private int curtainMinHeight;
    private float topRadius;
    private float bottomRadius;
    private RectF whiteBarRectF;
    private int whiteBarWidth;
    private int whiteBarHeight;
    private int whiteBarMarginBottom;
    private float translateY;
    private boolean isCurtainArea;
    private boolean isNotSet;
    private int deviceSolidBgColor;
    private int shapeSolidColor;

    public RollerShutterSeek(Context context) {
        this(context, null);
    }

    public RollerShutterSeek(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RollerShutterSeek(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public RollerShutterSeek(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initView(context, attrs);
    }

    public void initView(Context context, AttributeSet attrs) {
        progressTextColor = AppApplication.getInstance().getThemeColor(R.attr.secondaryColor6);
        deviceSolidBgColor = AppApplication.getInstance().getThemeColor(R.attr.deviceSolidBgColor);
        shapeSolidColor = AppApplication.getInstance().getThemeColor(R.attr.shapeSolidColor);
        progressTextSize = dp2px(16);
        mRootRect = new Rect();
        topLineHeight = dp2px(30);
        bottomHeight = dp2px(36);
        curtainMarginLeftRight = dp2px(12);
        curtainFillHeight = dp2px(29);
        curtainGapHeight = dp2px(8);

        mPaint = new Paint();
        mPaint.setAntiAlias(true);

        mTextPaint = new TextPaint();
        mTextPaint.setAntiAlias(true);

        topLinePath = new Path();
        bgRectF = new RectF();
        curtainMinHeight = dp2px(29f);
        topRadius = dp2px(12f);
        bottomRadius = dp2px(12f);
        whiteBarWidth = dp2px(36);
        whiteBarHeight = dp2px(5);
        whiteBarMarginBottom = dp2px(6);
        whiteBarRectF = new RectF();
        clickThreshold = dp2px(3);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int dw = getMeasuredWidth();
        int dh = getMeasuredHeight();
        mRootRect.left = 0;
        mRootRect.top = 0;
        mRootRect.right = dw;
        mRootRect.bottom = dh;
        mTrackLength = dh - bottomHeight - topLineHeight - curtainMinHeight;
        bgRectF.left = curtainMarginLeftRight;
        bgRectF.top = 0;
        bgRectF.right = dw - curtainMarginLeftRight;
        bgRectF.bottom = dh - bottomHeight;
        whiteBarRectF.left = (dw - whiteBarWidth) / 2f;
        whiteBarRectF.top = bgRectF.bottom - whiteBarMarginBottom - whiteBarHeight;
        whiteBarRectF.right = whiteBarRectF.left + whiteBarWidth;
        whiteBarRectF.bottom = whiteBarRectF.top + whiteBarHeight;
    }

    @Override
    protected void onDraw(Canvas canvas) {
//        float level = currentTrackLength / mLeftRect.width();
////        mLeftRect.right = (int) (getRatio() * leftRightCurtainWidth);
////        mRightRect.left = (int) (mRootRect.width() - getRatio() * leftRightCurtainWidth);
////        mLeftDrawable.setBounds(mLeftRect);
////        mRightDrawable.setBounds(mRightRect);
//        leftDragRect.left = (int) (leftCurtainMarginLeft + currentTrackLength - mLeftDragDrawable.getIntrinsicWidth() / 2);
//        leftDragRect.right = (int) (leftCurtainMarginLeft + currentTrackLength + mLeftDragDrawable.getIntrinsicWidth() / 2);
//        rightDragRect.left = (int) (mRootRect.width() - currentTrackLength - rightCurtainMarginRight) - mRightDragDrawable.getIntrinsicWidth() / 2;
//        rightDragRect.right = (int) (mRootRect.width() - currentTrackLength - rightCurtainMarginRight) + mRightDragDrawable.getIntrinsicWidth() / 2;
//        mLeftDragDrawable.setBounds(leftDragRect);
//        mRightDragDrawable.setBounds(rightDragRect);
//        mLeftDragDrawable.draw(canvas);
//        mRightDragDrawable.draw(canvas);
        //画阴影背景
        mPaint.setShadowLayer(dp2px(12), 0, dp2px(10), 0x2225334b);
        mPaint.setColor(deviceSolidBgColor);
        canvas.drawRoundRect(bgRectF, bottomRadius, bottomRadius, mPaint);
        mPaint.clearShadowLayer();

        //画窗帘
        canvas.save();
        translateY = (1 - getRatio()) * mTrackLength;
        canvas.translate(0, -translateY);
        float radius = 0;
        if (translateY <= bottomRadius) {
            radius = bottomRadius - translateY;
        }
        for (int i = 0; i < 5; i++) {
            mPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
            int top = topLineHeight + i * (curtainFillHeight + curtainGapHeight);
            canvas.drawRect(curtainMarginLeftRight, top, getWidth() - curtainMarginLeftRight, top + curtainFillHeight, mPaint);
            mPaint.setColor(0x00000000);
            canvas.drawRect(curtainMarginLeftRight, top + topLineHeight, getWidth() - curtainMarginLeftRight, top + topLineHeight + curtainGapHeight, mPaint);
        }
        mPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
        topLinePath.reset();
        topLinePath.moveTo(curtainMarginLeftRight, bgRectF.bottom - radius);
        topLinePath.quadTo(curtainMarginLeftRight, bgRectF.bottom, curtainMarginLeftRight + radius, bgRectF.bottom);
        topLinePath.lineTo(bgRectF.right - radius, bgRectF.bottom);
        topLinePath.quadTo(bgRectF.right, bgRectF.bottom, bgRectF.right, bgRectF.bottom - radius);
        topLinePath.lineTo(bgRectF.right, bgRectF.bottom - curtainFillHeight);
        topLinePath.lineTo(curtainMarginLeftRight, bgRectF.bottom - curtainFillHeight);
        topLinePath.lineTo(curtainMarginLeftRight, bgRectF.bottom - radius);
        topLinePath.close();
        canvas.drawPath(topLinePath, mPaint);
        mPaint.setColor(0xffffffff);
        canvas.drawRoundRect(whiteBarRectF, whiteBarHeight, whiteBarHeight, mPaint);
        canvas.restore();

        //画固定顶部
        mPaint.setColor(shapeSolidColor);
        //遮住窗帘滑动时顶部的圆角
        canvas.drawRect(bgRectF.left, 0, bgRectF.right, topLineHeight, mPaint);
        mPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor5));
        topLinePath.reset();
        topLinePath.moveTo(curtainMarginLeftRight, topRadius);
        topLinePath.quadTo(curtainMarginLeftRight, 0, curtainMarginLeftRight + topRadius, 0);
        topLinePath.lineTo(bgRectF.right - topRadius, 0);
        topLinePath.quadTo(bgRectF.right, 0, bgRectF.right, topRadius);
        topLinePath.lineTo(bgRectF.right, topLineHeight);
        topLinePath.lineTo(curtainMarginLeftRight, topLineHeight);
        topLinePath.lineTo(curtainMarginLeftRight, topRadius);
        topLinePath.close();
        canvas.drawPath(topLinePath, mPaint);

        //画进度文字
        String progressText = null;
        if(isNotSet){
            progressText = getResources().getString(R.string.not_set);
        }else{
            progressText = (100 - mProgress) + "%";
        }
        mTextPaint.setTextSize(progressTextSize);
        int textX = (int) (getWidth() - mTextPaint.measureText(progressText)) / 2;
        mTextPaint.setColor(progressTextColor);
        canvas.drawText(progressText, textX, getHeight() - mTextPaint.getFontMetrics().bottom, mTextPaint);
    }

    public void setProgress(int value) {
        mProgress = value;
        correctProgress();
        isNotSet = false;
        invalidate();
    }

    public void isNotSet(boolean isNotSet) {
        this.isNotSet = isNotSet;
        mProgress = 0;
        invalidate();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!isEnabled()) return true;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                markDownEvent(event);
                checkDragArea(true);
                break;
            case MotionEvent.ACTION_MOVE:
                if (isReadyDrag) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                    updateDrag(event);
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                float upX = event.getX();
                float upY = event.getY();
                getParent().requestDisallowInterceptTouchEvent(false);
                if (mOnChangeListener != null && isReadyDrag) {
                    playSoundEffect(SoundEffectConstants.CLICK);
                    mOnChangeListener.onValueChanged(mProgress);
                }
                float clickDistance = (float) Math.sqrt(Math.pow(Math.abs(upX - mDownEvent.downPositionX), 2) + Math.pow(Math.abs(upY - mDownEvent.downPositionY), 2));
                if (clickDistance <= clickThreshold) {
                    playSoundEffect(SoundEffectConstants.CLICK);
                    updateClick(event);
                    invalidate();
                }
                isReadyDrag = false;
                isCurtainArea = false;
                isNotSet = false;
                break;
        }
        return true;
    }

    private void updateClick(MotionEvent event) {
        int div = (int) (event.getY() - topLineHeight - curtainMinHeight);
        div = div < 0 ? 0 : div;
        int progress = (int) track2progress(div);
        if (progress < mMax * 0.05f) progress = 0;
        if (progress > mMax * 0.95f) progress = mMax;
        mProgress = progress;
        if (mOnChangeListener != null) {
            mOnChangeListener.onProgressChanged(mProgress);
            mOnChangeListener.onValueChanged(mProgress);
        }
    }

    private void updateDrag(MotionEvent event) {
        int track = (int) (event.getY() - mDownEvent.downPositionY);
        mProgress = mDownEvent.progress + (int) track2progress(track);
        correctProgress();
        if (mOnChangeListener != null) {
            mOnChangeListener.onProgressChanged(mProgress);
        }
        isNotSet = false;
        invalidate();
    }

    /**
     * 检查拖拉区域
     *
     * @param isAllProgress 是否是进度的全部区域
     */
    private void checkDragArea(boolean isAllProgress) {
        if (isAllProgress) {
            isCurtainArea = mDownEvent.downPositionX >= curtainMarginLeftRight && mDownEvent.downPositionX <= getWidth() - curtainMarginLeftRight
                    && mDownEvent.downPositionY >= topLineHeight && mDownEvent.downPositionY <= bgRectF.bottom - translateY;
            postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (isCurtainArea) {
                        isReadyDrag = true;
                        if (mOnChangeListener != null) mOnChangeListener.onStartTrackingTouch();
                    } else {
                        isReadyDrag = false;
                    }
                }
            }, CAN_DRAG_TIME);
        } else {
            //todo 指定区域拖动
        }
    }

    /**
     * 进度比例
     *
     * @return
     */
    protected float getRatio() {
        return mProgress * 1.0f / mMax;
    }

    /**
     * 拉动轨迹换算成progress
     *
     * @param track
     * @return
     */
    public float track2progress(int track) {
        return track * 1.0f / mTrackLength * mMax;
    }

    protected class ActEvent {
        int progress;
        long downTime;
        float downPositionX;
        float downPositionY;
    }

    protected ActEvent mDownEvent = new ActEvent();

    protected void markDownEvent(MotionEvent event) {
        mDownEvent.progress = mProgress;
        mDownEvent.downTime = event.getEventTime();
        mDownEvent.downPositionX = event.getX();
        mDownEvent.downPositionY = event.getY();
    }

    public void correctProgress() {
        if (mProgress >= mMax) {
            mProgress = mMax;
        }
        if (mProgress <= 0) {
            mProgress = 0;
        }
    }

    /**
     * 进度监听
     */
    public interface OnChangeListener {
        /**
         * 进度条的更新
         *
         * @param progress
         */
        public void onProgressChanged(int progress);

        /**
         * 开始拖动
         */
        public void onStartTrackingTouch();

        /**
         * 停止拖动 确认进度值
         */
        public void onValueChanged(int progress);
    }

    public void setOnChangeListener(OnChangeListener changeListener) {
        mOnChangeListener = changeListener;
    }

    /**
     * dp转px
     *
     * @param dp dp值
     * @return px值
     */
    public int dp2px(float dp) {
        return (int) (getResources().getDimension(R.dimen.dp_1) * dp);
    }
}
